package website

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"time"
)

const (
	LevelDebug = iota
	LevelFatal
	LevelError
	LevelWarn
	LevelInfo
)

var (
	level   = LevelInfo
	ops_log = log.New(os.Stdout, "", log.Lshortfile|log.LstdFlags)
)

func InitLogger(cfg *Config) {
	logfile, err := os.OpenFile(filepath.Join(cfg.LogDir, time.Now().Format("2006-01-02")+".log"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		logFatal(err)
	}
	ops_log.SetOutput(logfile)
	ops_log.SetFlags(log.LstdFlags)
}

func LogLevel() int {
	return level
}

func SetLogLevel(l int) {
	level = l
}

func SetLogger(l *log.Logger) {
	ops_log = l
}

func logInfo(err ...interface{}) {
	if level <= LevelInfo {
		logPrintln("[INFO]", err...)
	}
}

func logFatal(err ...interface{}) {
	if level <= LevelFatal {
		logPrintln("[FATAL]", err...)
	}
}

func logWarn(err ...interface{}) {
	if level <= LevelWarn {
		logPrintln("[WARN]", err...)
	}
}

func logDebug(err ...interface{}) {
	if level <= LevelDebug {
		logPrintln("[DEBUG]", err...)
	}
}

func logError(err ...interface{}) {
	if level <= LevelError {
		logPrintln("[ERROR]", err...)
	}
}

func logPrintln(msgType string, err ...interface{}) {
	errStr := fmt.Sprintf("%v", err)
	funcName, file, line, ok := runtime.Caller(2)

	logDate := time.Now().Format("2006/01/02 15:04:05")
	if ok {
		name := runtime.FuncForPC(funcName).Name()
		file = filepath.Base(file)
		fmt.Fprintln(os.Stdout, msgType, logDate, file, line, name, errStr)
		ops_log.SetPrefix(msgType)
		ops_log.Println(file, line, name, err)
	} else {
		fmt.Fprintln(os.Stdout, msgType, logDate, errStr)
		ops_log.SetPrefix(msgType)
		ops_log.Println(err)
	}
}
